package command

import (
	"fmt"
	"strings"
	"time"

	"github.com/pkg/errors"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"
)

type Reset struct {
	BaseCommand
	Node      *confv1beta1.Node
	BKEConfig string
	Extra     []string

	// DeepRestore is used to restore the node to the initial state
	DeepRestore bool
}

func (r *Reset) Validate() error {
	if r.BKEConfig == "" {
		return errors.New("bkeConfig is empty")
	}
	if r.Node == nil {
		return errors.New("nodes is empty")
	}
	return r.BaseCommand.validate()
}

func (r *Reset) New() error {
	if err := r.Validate(); err != nil {
		return err
	}
	commandName := fmt.Sprintf("%s%s-%d", ResetNodeCommandNamePrefix, r.Node.IP, time.Now().Unix())
	bkeConfig := fmt.Sprintf("bkeConfig=%s:%s", r.NameSpace, r.BKEConfig)
	extra := fmt.Sprintf("extra=%s", strings.Join(r.Extra, ","))

	var scope string
	if r.DeepRestore {
		scope = fmt.Sprintf("scope=cert,manifests,kubelet,container,containerRuntime,source,extra")
	} else {
		scope = fmt.Sprintf("scope=cert,manifests,kubelet,container,extra")
	}

	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		{
			ID: "reset",
			Command: []string{
				"Reset",
				bkeConfig,
				scope,
				extra,
			},
			Type:          agentv1beta1.CommandBuiltIn,
			BackoffIgnore: false,
		},
	}
	//commandSpec.NodeName = b.Node.Hostname

	nodes := bkenode.Nodes{*r.Node}
	commandSpec.NodeSelector = getNodeSelector(nodes)
	return r.newCommand(commandName, BKEMachineLabel, commandSpec)
}

// Wait wait for command execution completion displayed
func (r *Reset) Wait() (error, []string, []string) {
	err, _, successNodes, failedNodes := r.waitCommandComplete()
	return err, successNodes, failedNodes
}
